from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.core.urlresolvers import reverse
from .. import models
from django.core.paginator import Paginator
# 添加
def catesadd(request):
    if request.method == 'GET':
        oob=models.Cates.objects.extra(select={'paths':'concat(path,id)'}).order_by('paths')

        return render(request,'myadmin/cates/add.html',{'info':oob})
    elif request.method == 'POST':
        data = request.POST.dict()
        
        ob=models.Cates()
        ob.name=data['name']
        ob.pid=int(data['fname'])

        if ob.pid !=0:
            f=models.Cates.objects.get(id=data['fname'])
            ob.path=f.path+str(ob.pid)+','
        else:
            ob.path=data['fname']+','
        ob.save()
        ob=models.Cates.objects.all()
        return render(request,'myadmin/cates/userlist.html',{'info':ob})

def cateslist(request):
    ob =models.Cates.objects.extra(select={'paths':'concat(path,id)'}).order_by('paths')
    # extra(select={'paths':'concat(path,id)'}).order_by('paths')
    # for i in ob:
    #     print(i.path.count(',')-1)
    p = Paginator(ob,10)
    # 统计所有的数据
    # sum_data=p.count
    # 获取可以分多少页 
    page_num=p.num_pages
    # 分页的范围 range(1,)
    pagenums = p.page_range   
    # 接受页码
    pg = int(request.GET.get('p',1))
    # 判断当前页码不能小于1
    if pg<1:
        pg=1
    if pg>page_num:
        pg=page_num
    # 获取第几页的数据
    pagedata = p.page(pg)
    # 限制边界 如果当前页码小于或=3 只区前五条数据
    # 
    if pg <= 3:
        pag_list=pagenums[:5]
    elif pg+2> page_num:
         pag_list=pagenums[-5:]
    else:
        pag_list=pagenums[pg-3:pg+2]
    print(pag_list)


    return render(request,'myadmin/cates/userlist.html',{'info':pagedata,'pagenums':pag_list,'pg':pg})
# 删除
def catesdel(request):
    cid=request.GET.get('id')
    ob=models.Cates.objects.filter(pid=cid)
    if ob:
        return JsonResponse({'error':0,'msg':'有子分类不能删除'})
    else:
        cb=models.Cates.objects.get(id=cid)
        cb.delete()
        return JsonResponse({'error':1,'msg':'删除成功'})
# 修改
def catesre(request):
    data=request.GET.dict()

    try:
        ob=models.Cates.objects.get(id=data['id'])
        ob.name=data['name']
        ob.save()
        return JsonResponse({'error':1,'msg':'修改成功'})
    except:
        return JsonResponse({'error':0,'msg':'修改失败'})
